package common;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import domain.WebBean;

public class ReadConfig {

	public static String path = "config/web.xml";

	@SuppressWarnings("unchecked")
	public static List<WebBean> read() throws Exception {
		// 创建SAXReader对象
		SAXReader reader = new SAXReader();
		// 读取文件 转换成Document
		Document document = reader.read(new File(path));
		// 获取根节点元素对象
		Element root = document.getRootElement();
		List<Element> elements = root.elements();
		List<WebBean> webBeans = new ArrayList<>();
		for (Element element : elements) {
			WebBean webBean = new WebBean();
			webBean.setUrl(element.element("url").getStringValue());
			webBean.setFids(getFids(element.element("fids").getStringValue()));
			webBean.setUsers(getUsreInfo(element.element("users").getStringValue()));
			webBeans.add(webBean);
		}
		return webBeans;
	}

	public static List<String> getFids(String fids) {
		List<String> fidlist = new ArrayList<>();
		for (String fid : fids.split(",")) {
			fidlist.add(fid);
		}
		return fidlist;
	}

	public static Map<String, String> getUsreInfo(String userInfo) {
		Map<String, String> userMap = new HashMap<>();
		for (String user : userInfo.split(";")) {
			String[] userI = user.split(",");
			if (userI.length == 2) {
				userMap.put("userName", userI[0]);
				userMap.put("password", userI[1]);
			}
		}
		return userMap;
	}
}
